from server.app.cloud_ide.schema.ide_registry.request.ide_registry_create_request import IdeRegistryCreateRequest
from server.app.cloud_ide.schema.ide_registry.request.ide_registry_update_request import IdeRegistryUpdateRequest
from server.app.cloud_ide.service.ide_registry_service import IdeRegistryService
from behave import *

from server.framework.core.database import SessionLocal
from server.framework.core.logger import logger

ide_registry_service = IdeRegistryService()
db = SessionLocal()


@step('查看镜像源详情列表')
def 查看镜像源详情列表(context):
    ide_registry_service.get_ide_registry_list(db=db, page_size=10, current_page=1,
                                               name=None, enable=None)


@step('新增镜像源,信息如下')
def 新增镜像源_信息如下(context):
    for row in context.table:
        rs = ide_registry_service.create_ide_registry(db=db, data=IdeRegistryCreateRequest(
            name=row['name'],
            registry=row['registry'],
            enable=row['enable']
        ))
        assert rs


@step('查看镜像源[{name}]的详情信息')
def 查看镜像源_的详情信息(context, name):
    target = ide_registry_service.find_ide_registry_by_name(db=db, name=name)
    rs = ide_registry_service.get_ide_registry_by_id(db, target.id)
    assert rs is not None


@step('删除以下镜像源')
def 删除以下镜像源(context):
    names = [x['name'] for x in context.table]
    for name in names:
        target = ide_registry_service.find_ide_registry_by_name(db=db, name=name)
        if target is not None:
            ide_registry_service.delete_ide_registry(db=db, ids=[str(target.id)])


@step('编辑镜像源[{name}]的详情信息,将镜像源信息修改为')
def 编辑镜像源_的详情信息_将镜像源信息修改为(context, name):
    target = ide_registry_service.find_ide_registry_by_name(db=db, name=name)
    for row in context.table:
        rs = ide_registry_service.update_ide_registry(db=db, data=IdeRegistryUpdateRequest(
            name=row['name'],
            registry=row['registry'],
            enable=row['enable'],
            id=str(target.id)
        ))
        assert rs
